package com.dayu.tcp.common;

import com.dayu.tcp.common.util.StrUtil;
import lombok.Getter;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

public class Sequence {
    private Sequence() {
    }

    @Getter
    private static final Sequence instance = new Sequence();

    private final ConcurrentMap<String, AtomicInteger> sequenceMap = new ConcurrentHashMap<>();

    public Integer addAndGet(String sequenceName, int step) {
        if (StrUtil.isBlank(sequenceName)) {
            return null;
        }
        AtomicInteger sequence;
        AtomicInteger ret = sequenceMap.get(sequenceName);
        if (ret == null) {
            sequence = new AtomicInteger();
            sequenceMap.put(sequenceName, sequence);
        } else {
            sequence = ret;
        }
        return sequence.addAndGet(step);
    }

    public Integer addAndGet(String sequenceName) {
        return addAndGet(sequenceName, 1);
    }

}
